import os
import sys
import requests
from PyQt5.QtWidgets import (
    QApplication,
    QWidget,
    QMessageBox
)
from PyQt5 import (
    QtCore,
    QtGui,
    QtWidgets
)
import time


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(711, 567)
        self.layoutWidget = QtWidgets.QWidget(Form)
        self.layoutWidget.setGeometry(QtCore.QRect(20, 10, 681, 551))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.label_4 = QtWidgets.QLabel(self.layoutWidget)
        self.label_4.setObjectName("label_4")
        self.verticalLayout.addWidget(self.label_4)
        spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(self.layoutWidget)
        self.label.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.verticalLayout.addLayout(self.horizontalLayout)
        spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem2)
        self.listWidget = QtWidgets.QListWidget(self.layoutWidget)
        self.listWidget.setObjectName("listWidget")
        self.verticalLayout.addWidget(self.listWidget)
        spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem3)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem4)
        self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)
        spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem5)
        self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout_2.addWidget(self.pushButton_3)
        spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem6)
        self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_2.addWidget(self.pushButton_2)
        spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem7)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_2 = QtWidgets.QLabel(self.layoutWidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_3.addWidget(self.label_2)
        spacerItem8 = QtWidgets.QSpacerItem(58, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem8)
        self.label_3 = QtWidgets.QLabel(self.layoutWidget)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_3.addWidget(self.label_3)
        spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem9)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "不落的音乐下载器"))
        self.label_4.setText(_translate("Form", "音乐下载器"))
        self.label.setText(_translate("Form", "请输入歌手名称："))
        self.pushButton.setText(_translate("Form", "点击搜索"))
        self.pushButton.clicked.connect(Form.btn_search)
        self.pushButton_3.setText(_translate("Form", "清空"))
        self.pushButton_3.clicked.connect(Form.btn_clear)
        self.pushButton_2.setText(_translate("Form", "下一页"))
        self.pushButton_2.clicked.connect(Form.btn_next)
        self.label_2.setText(_translate("Form", "软件仅供开发学习交流，禁止商用，违者后果自负"))
        self.label_3.setText(_translate("Form", "    made   by  不落"))
        self.listWidget.itemDoubleClicked.connect(Form.download)


class Window(QWidget):

    def __init__(self):
        super().__init__()  # 调用父类的初始化方法
        self.ui = Ui_Form()  # 初始化UI对象
        self.ui.setupUi(self)  # 设置UI界面
        self.page = 1  # 初始化页码
        self.dic = {}  # 初始化一个空字典，用于存储数据

    def btn_search(self, page):
        '''
        搜索按钮槽函数
        :param page: 1   默认为1 使用翻页按钮自增
        内置爬虫程序，实现对歌曲的搜索功能，在列表框显示
        歌手名，歌曲名，歌曲id
        '''
        text = self.ui.lineEdit.text()

        res = requests.post(
            url="https://zz123.com/ajax/",
            data={
                "act": "search",
                "key": text,  # 歌手名
                "lang": "",
                "page": page,  # 页码
            }
        )

        res_dict = res.json()
        data_list = res_dict['data']
        for data in data_list:
            mp3_id = data['id']
            mp3_name = data['mname']
            singer_name = data['sname']

            item = f'{data["play_time"]}【 {mp3_name} 】- {singer_name}'
            self.dic[item] = mp3_id
            self.ui.listWidget.addItem(item)

    def btn_next(self):
        '''
       页码翻页按钮，实现对页码的递增

       '''
        self.page += 1
        self.btn_search(self.page)

    def download(self, item):

        '''
        列表框双击事件，实现对歌曲的下载
        :param item: 列表框中的item
        '''
        key = item.text()
        file_name = key.replace('---------', '')
        ids = self.dic[key]

        mes = QMessageBox.question(
            self,
            '下载提示',
            '是否下载该歌曲？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.Yes
        )

        if mes == QMessageBox.Yes:
            self.get_(ids, file_name)

    def btn_clear(self):
        self.ui.listWidget.clear()
        self.ui.lineEdit.clear()

    def get_(self, ids, file_name):
        response = requests.post('https://zz123.com/ajax/', data={
            'act': 'songinfo',
            'id': ids,
        }).json()
        url = response.get('data', {}).get('mp3')

        if url is None or url == '':
            QMessageBox.critical(
                self,
                '错误',
                '歌曲链接解析失败！',
                QMessageBox.Ok
            )
            return

        music_content = requests.get(url=url).content
        if not os.path.exists('下载'):
            os.mkdir('下载')
        with open(f'下载/{file_name}.mp3', 'wb') as f:
            f.write(music_content)
        QMessageBox.information(self, '下载提示', '下载成功！')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
